$Focus.fScaleFactor = 1.1;
window.$Page = new Page({
    properties: {
        UI:"subscribe",
        strInitFocusElementId: "order_cell_0",
        oPageContext:{},
        bIsContentListDataInit:false,
        oAdjacency: {
            "order_cell_0": {"up": "", "right": "order_cell_1", "down": "", "left": ""},
            "order_cell_1": {"up": "", "right": "order_cell_2", "down": "", "left": "order_cell_0"},
            "order_cell_2": {"up": "", "right": "back", "down": "back", "left": "order_cell_1"},
            "back": {"up": "order_cell_2", "right": "", "down": "", "left": "order_cell_2"}
        }
    },
    run:function () {
        if($URL.getQueryStringByName("referURL")=='quiet'){
            $HB.initQuietBack();//返回处理
            return;
        }
        $Page.onPageKeyDown = function(){};//禁掉原来按键
        try {
            if($URL.getQueryStringByName("backStatus") != '1'){
                if($URL.getQueryStringByName('mediaId')){
                    $Probe.mediaId=$URL.getQueryStringByName('mediaId');
                    $Log.info("$Probe.mediaId::"+$Probe.mediaId);
                    $HB.getMediaCode($Probe.mediaId,0,function(aMediaCode){
                        $HB.Auth(null, aMediaCode[0], function(){
                            $Log.warn("mediacode=>"+aMediaCode[0]);
                            $Log.warn("HB.strOrderUrl==>"+$HB.strOrderUrl);
                            window.parent.location.href = $HB.EPGDomain+"?spVodPlayUrl="+encodeURIComponent($HB.strOrderUrl);//文档原有的
                        });
                    });
                }else{
                    $HB.Auth(null, null, function(){
                        $Log.warn("HB.strOrderUrl==>"+$HB.strOrderUrl);
                        window.parent.location.href = $HB.EPGDomain+"?spVodPlayUrl="+encodeURIComponent($HB.strOrderUrl);//文档原有的
                    });
                }
                
            }else{
                $HB.Auth(null, null, function(){
                    if(parseInt($Cookie.get('isAuthenticated')) == 1){
                        var strBackPath = $Page.getBackURL();
                        if(-1 != strBackPath.split("?")[0].indexOf("active_luckydraw")){
                            strBackPath += "&businessCode="+$URL.getQueryStringByName("businessCode");
                        }
                        window.location.href = strBackPath;
                    }else{
                        $HB.getProbability(function(){
                            $HB.Auth(null,null,function(){
                                var strBackPath = $Page.getBackURL();
                                if(-1 != strBackPath.split("?")[0].indexOf("active_luckydraw")){
                                    strBackPath += "&businessCode="+$URL.getQueryStringByName("businessCode");
                                }
                                window.location.href = strBackPath;
                            });
                        });
                    }
                    
                });
               
            }
        } catch (error) {
            
        }
        return;
        
        if($URL.getQueryStringByName("referURL")=='quiet'){
            $HB.initQuietBack();//返回处理
            return;
        }
        for (var i=0;i<3;i++){
            var img = new Image;
            img.src = "image/bg_"+i+".jpg";
        }
        var strReferURLNow=decodeURIComponent($URL.getQueryStringByName('referURL'));
        if (0 == strReferURLNow.indexOf('[') && !$Probe.mediaId){//如果referURL开头是数组
            var arrSplitRefer = JSON.parse(strReferURLNow);
            var strBackUrl = arrSplitRefer.pop();//上一个页面的
            if(-1!=strBackUrl.indexOf('vPlayerFull')){
                $Probe.mediaId=$URL.getStringByName(strBackUrl,'mediaId');//获取节目的Id
            }
        }
        if($URL.getQueryStringByName('mediaId')){
            $Probe.mediaId=$URL.getQueryStringByName('mediaId');
            $Log.info("$Probe.mediaId::"+$Probe.mediaId);
            $HB.getMediaCode($Probe.mediaId,0,function(aMediaCode){
                $Page.changeMediaCode(aMediaCode,function(){
                    $Page.initData();
                });
            });
            $Page.checkPageReadyAndInitFocus();
        }else{
            $Page.initData();
        }
        if($URL.getQueryStringByName('code')){
            $Probe.code=$URL.getQueryStringByName('code');
        }
        $Probe.module="Other";
        $Page.checkPageReadyAndInitFocus();
    },
    getBackURL : function(){
        if($Config.PAGES[$Page.strPageDefaultBackUI]){
			$Page.strPageDefaultBackUI = $Config.PAGES[$Page.strPageDefaultBackUI];
		}
		var strReferUrl = decodeURIComponent($URL.getQueryStringByName("referURL"));
		try{
			if(!strReferUrl&&$Page.strPageDefaultBackUI||0 == strReferUrl.indexOf('[')&&!JSON.parse(strReferUrl).length){
				if (0 == $Page.strPageDefaultBackUI.indexOf('http')) {
					strReferUrl = $Page.strPageDefaultBackUI;
				}else{
					//window.location.href = $Circumstance.TOPDRAW_EPG_SERVER + $Page.strPageDefaultBackUI;
					strReferUrl = $Constant.ROOT_DIR + $Page.strPageDefaultBackUI;
				}
				return;
			}
		}catch(err){
			$Log.error("error in judge default back==>"+err);
		}
		if (0 == strReferUrl.indexOf('[')) {//如果是新版数组referURL
			var arrSplitRefer = JSON.parse(strReferUrl);
			var strBackUrl = arrSplitRefer.pop();//上一个页面的url

			if (strBackUrl == '_') {//规定路径返回
				strBackUrl = $Page.strPageDefaultBackUI ? $Page.strPageDefaultBackUI : '' + '?backStatus=1&';
				if (arrSplitRefer[0]) {//string,backpage之后的referURL
					strReferUrl = JSON.stringify(arrSplitRefer);
				} else {
					strReferUrl = strReferUrl.substr(strReferUrl.indexOf(']') + 1);
				}
			} else {
				if (arrSplitRefer[0]) {//string,backpage之后的referURL
					strReferUrl = JSON.stringify(arrSplitRefer);
				} else {
					strReferUrl = strReferUrl.substr(strReferUrl.indexOf(']') + 1);
				}
			}
			try {
				if (0==strBackUrl.indexOf("http://")) {
					strReferUrl = strBackUrl;
				}else if(0==strBackUrl.indexOf("http%3A%2F%2F")){
					strReferUrl = decodeURIComponent(strBackUrl);
				}else{
					var aBackURLSegments = strBackUrl.split("?");
					aBackURLSegments[0] = $Config.PAGES[aBackURLSegments[0]] || aBackURLSegments[0];
					strBackUrl =  aBackURLSegments[0] + (aBackURLSegments[1] ? "?" + aBackURLSegments[1] : "");
					strReferUrl = $Constant.ROOT_DIR + strBackUrl + (strBackUrl.indexOf('?') == -1 ? '?referURL=' : '&referURL=') + encodeURIComponent(strReferUrl);
				}
			}catch(err){
				$Log.error("back error==>"+err);
			}
		} 
        return strReferUrl;
    },
    initData:function(){
        //判断订购是否直接返回
        if($Page.oPageContext.bIsFromDX){
            $Page.oPageContext.bIsFromDX=null;
            $Page.strProductId=$Page.oPageContext.productId;//获得请求的产品Id
            $Page.oPageContext.productId=null;
        }
        if ($URL.getQueryStringByName("businessCode")) {
            $Page.strProductId = $URL.getQueryStringByName('productId')||"productId";
            $Probe.transactionId = $URL.getQueryStringByName('transactionId')||"-1";
            $Page.strProductPrice = $URL.getQueryStringByName('productPrice')||"0";
            if ($URL.getQueryStringByName("businessCode") == "success") {
                $Page.onPageKeyDown = function(){};//不允许返回操作，防止意外，因为返回又jm订购处理，成功之后按照自动返回处理即可
                $Dom.getById("other_mask").innerHTML = '订购成功!';
                if ($Page.strProductId) {
                    for (var i = 0; i < $Config.GlOBAL_VALUE_ADDED_PRODUCT_ID.length; i++) {
                        if ($Page.strProductId == $Config.GlOBAL_VALUE_ADDED_PRODUCT_ID[i]) {
                            $Cookie.set('isAuthenticated', '1');
                            break;
                        }
                    }
                }
                $Probe.orderResult=0;//成功
            } else {
                $Dom.getById("other_mask").innerHTML = '订购失败!';
                $Probe.orderResult=-1;//失败
            }
            $Dom.getById("other_mask").style.display = 'block';
            $Page.orderBackProbe();
            if ($Page.timerTip) {
                clearTimeout($Page.timerTip)
            }
            $Page.timerTip = setTimeout(function () {
                if ($URL.getQueryStringByName("businessCode") == "success") {
                    $URL.backAPage();
                } else {
                    $Dom.getById("other_mask").style.display = 'none';
                }
            }, 2500)
        }else{
            //电信方把返回地址自己拼在forwardUrl里面了,所以进入订购页一定要请求一次鉴权，获取地址
            // $Page.isAuthStatus=$Cookie.get('isAuthenticated');//鉴权结果
            // $HB.Auth(null,null);
        }
    },
    CoummunicationError:function(responseText,oAddtional){//通用的通讯错误请求的调用
        $Log.error('Coummunication: '+oAddtional.error+' Error...'+responseText+'!!');
    },
    SwitchTab:function () {

    },
    order:function (productId,productType,vorderFrom) {
        $Page.strProductId = productId;
        $Page.strVorderFrom = vorderFrom;
        $Page.strProductType = productType;

        if($Page.isClickOrder==0){
            return;
        }

        var strCookiePageContext = $Cookie.get($Constant.TOPDRAW_PAGE_CONTEXT_KEY);
        var oCookiePageContext = null;
        if (!strCookiePageContext || strCookiePageContext == "") {
            oCookiePageContext = {pageContext: [], bIsFromDX: true};
        } else {
            oCookiePageContext = JSON.parse(strCookiePageContext);
            oCookiePageContext.bIsFromDX = true; //记录页面是否从电信订购页面来
        }
        oCookiePageContext.productId=$Page.strProductId;//存储下productId;
        oCookiePageContext.promotionName=$Page.promotionName;
        if(!oCookiePageContext.referURLFromDX){//假如没有保存referURL时
            oCookiePageContext.referURLFromDX=$URL.getQueryStringByName('referURL');//referURL保存在cookie
        }

        $Page.pushContext();

        $Page.goOrderProbe();
        // filterAwayProbe();//离开的探针
        // $Page.isClickOrder=0;

        $Page.pushContext();
        $HB.orderProductHB($Page.strProductId,$Page.strProductType,$Page.strVorderFrom,$Page.strMediaCode);

    },
    changeMediaCode:function(aMediaCode,cb) {
        $Log.info(JSON.stringify(aMediaCode));
        $Log.info(JSON.stringify(aMediaCode));
        $Log.info(JSON.stringify(aMediaCode));
        $Page.strMediaCode = aMediaCode[0];
        $Probe.mediaCode=aMediaCode[0];
        //$HB.Auth(null,aMediaCode[0],cb);
        cb&&cb();
        $Log.warn('mediaCode='+$Probe.mediaCode);
    },
    goOrderProbe:function(){//去订购的探针
        $Probe.productId=$Page.strProductId;
    //            g_oProbe.productPrice=g_strProductPrice;
        $Probe.transactionId= $Utility.uuid(32,16);//直接支付到是可以直接用
        $Probe.productPrice = 0;
        for (var i=0;i<$HB.aProductList.length;i++){
            if ($HB.aProductList[i].productId == $Page.strProductId){
                $Probe.productPrice = parseFloat($HB.aProductList[i].price);
                $Page.strProductName = $HB.aProductList[i].name;
            }
        }
        $Probe.productPrice = $Probe.productPrice=="undefined"?0:$Probe.productPrice;
        var oParam={
            "productId":$Probe.productId,
            "unitPrice":$Probe.productPrice,
            "mediaId":$Probe.mediaId,
            "mediaCode":$Probe.mediaCode,
            'orderMode':0,//jm1,正常0
            'transactionId':$Probe.transactionId
        };
        $Probe.Subscribing(oParam);
        $HB.requestHbProbe('order',{
            id:$Probe.productId,
            code:$Probe.mediaCode,
            name:$Page.strProductName
        });
    },
    orderBackProbe:function(){//订购返回结果的探针
        $Probe.productId=$Page.strProductId;
        $Probe.productPrice = $Page.strProductPrice || 0;
        $Probe.productPrice = $Probe.productPrice=="undefined"?0:$Probe.productPrice;
        // $Probe.requestProbe('subscribed');
        var oParam={
            "productId":$Probe.productId,
            "unitPrice":$Probe.productPrice,
            "mediaId":$Probe.mediaId,
            "mediaCode":$Probe.mediaCode,
            'orderMode':0,//jm1,正常0,
            "result":$Probe.orderResult,//订购结果 -1失败,0成功
            'transactionId':$Probe.transactionId
        };
        $Probe.Subscribed(oParam);

    },
    checkPageReadyAndInitFocus:function() {
        try{
            if (!$UARecognize.bIsUTBox) {
                $Focus.collect();
            }
            if(!$Focus.bFocusInited){
                var ele = $Dom.query("#"+$Page.strInitFocusElementId);
                if(!ele.doesDisplay()){
                    $Page.strInitFocusElementId = "order_cell_0";
                }
                $Focus.init($Page.strInitFocusElementId, $Page.onBeforeFocusChange, $Page.onAfterFocusChange);
                $Focus.elFocusContainer.removeClass("smooth_animation_300");
            }
        }catch(err){
            $Log.error("CheckPageReadyAndInitFocus Error"+err);
        }
    },
    onBeforeFocusChange:function(elPrevious, elTarget, strDirection) {
        if (elPrevious){
            elPrevious.removeClass("focus_active");
        }
    },
    onAfterFocusChange:function(elPrevious, elTarget, strDirection) {
        if (elTarget) {
            elTarget.addClass("focus_active");
            if(-1 != elTarget.id.indexOf("order_cell")){
                var index = elTarget.id.replace("order_cell_","");
                document.body.style.backgroundImage="url('image/bg_"+index+".jpg"+"')"
            }
        }
    },
    onPageKeyDown:function(e){
        e = e ? e : window.event;
        var keyCode = e.which ? e.which : e.keyCode;
        var bIsContinueBubbling=true;
        if(keyCode!=$Constant.KEY['KEY_VIRTUAL_PRESS']){
//                        $Probe.updateActive();//探针动作监听更新sessionId等
        }
        if (keyCode == $Constant.KEY["KEY_LEFT"] || keyCode == $Constant.KEY["KEY_UT_LEFT"]) {
            var elTarget = $Focus.find($Focus.aFocusTargets, $Focus.iFocusStatus, "left");
            if(elTarget==null){
                return;
            }
            $Focus.fly(elTarget, "left", $Focus.fScaleFactor, null);
        }
        if (keyCode == $Constant.KEY["KEY_RIGHT"] || keyCode == $Constant.KEY["KEY_UT_RIGHT"]) {
            var elTarget = $Focus.find($Focus.aFocusTargets, $Focus.iFocusStatus, "right");
            if(elTarget==null){
                return;
            }
            $Focus.fly(elTarget, "right", $Focus.fScaleFactor, null);
        }
        if (keyCode == $Constant.KEY["KEY_UP"] || keyCode == $Constant.KEY["KEY_UT_UP"]) {
            var elTarget = $Focus.find($Focus.aFocusTargets, $Focus.iFocusStatus, "up");
            if (null == elTarget) {
                return;
            }

            $Focus.fly(elTarget, "up", $Focus.fScaleFactor, null);
        }
        if (keyCode == $Constant.KEY["KEY_DOWN"] || keyCode == $Constant.KEY["KEY_UT_DOWN"]) {
            var elTarget = $Focus.find($Focus.aFocusTargets, $Focus.iFocusStatus, "down");
            if (null == elTarget) {
                return;
            }
            $Focus.fly(elTarget, "down", $Focus.fScaleFactor, null);
        }
        if(keyCode == $Constant.KEY["KEY_ENTER"] || keyCode == $Constant.KEY["KEY_OK"]){

        }
        if(keyCode == $Constant.KEY["KEY_BACK"]){
            // $Log.clear();
            $Page.onPageKeyDown = function(){};//防止多次发送jm探针
        }
        return bIsContinueBubbling;
    }
});
